import uuid
import numpy as np
import pyautogui

class WindowCapture:
    def capture_window1():
        import win32gui
        import win32ui
        import win32con
        import numpy as np
        from PIL import Image
        import easygui


        # 获取所有窗口标题
        window_titles = []
        def enum_cb(hwnd, results):
            if win32gui.IsWindowVisible(hwnd):
                window_titles.append(win32gui.GetWindowText(hwnd))
        win32gui.EnumWindows(enum_cb, None)

        # 选择要截图的窗口
        window_title = easygui.choicebox(msg="请选择要截图的窗口", choices=window_titles)
        hwnd = win32gui.FindWindow(None, window_title)

        # 获取窗口的设备上下文
        hwindc = win32gui.GetWindowDC(hwnd)
        srcdc = win32ui.CreateDCFromHandle(hwindc)
        memdc = srcdc.CreateCompatibleDC()

        # 获取窗口大小
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        width = right - left
        height = bottom - top

        # 创建位图并进行截图
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(srcdc, width, height)
        memdc.SelectObject(bmp)
        memdc.BitBlt((0, 0), (width, height), srcdc, (0, 0), win32con.SRCCOPY)

        # 转换格式为png并保存
        bmpinfo = bmp.GetInfo()
        bmpstr = bmp.GetBitmapBits(True)
        img = Image.frombuffer(
            'RGB',
            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
            bmpstr, 'raw', 'BGRX', 0, 1
        )
        img.save('screenshot.png', 'PNG')

        # 清理资源
        memdc.DeleteDC()
        win32gui.DeleteObject(bmp.GetHandle())
        srcdc.DeleteDC()
        win32gui.ReleaseDC(hwnd, hwindc)

        # 显示截图
        img.show()
        return img
    def capture_window2():
        import mss
        import pygetwindow as gw
        from PIL import Image
        import easygui
        import win32gui

        # 获取所有窗口标题
        window_titles = []
        def enum_cb(hwnd, results):
            if win32gui.IsWindowVisible(hwnd):
                window_titles.append(win32gui.GetWindowText(hwnd))
        win32gui.EnumWindows(enum_cb, None)

        # 选择要截图的窗口
        window_title = easygui.choicebox(msg="请选择要截图的窗口", choices=window_titles)

        # 获取窗口对象
        try:
            window = gw.getWindowsWithTitle(window_title)[0]
        except IndexError:
            print(f"未找到标题为 '{window_title}' 的窗口.")
            exit()

        # 获取窗口的位置和大小
        x, y, width, height = window.left, window.top, window.width, window.height

        # 打印窗口的位置和大小
        print(f"截取窗口的位置: ({x}, {y}), 大小: {width}x{height}")

        # 截取窗口
        with mss.mss() as sct:
            bbox = {'top': y, 'left': x, 'width': width, 'height': height}
            screenshot = sct.grab(bbox)

            # 将截取的结果转换为PIL图像格式
            img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')

            # 保存截取的图像
            img.save('screenshot_window.png')

        print("指定窗口的截图已保存.")
        return img
    def capture_window3():
        import mss
        import pygetwindow as gw
        import easygui
        from PIL import Image

        # 获取所有窗口标题
        window_titles = gw.getAllTitles()

        # 选择要截图的窗口
        window_title = easygui.choicebox(msg="请选择要截图的窗口", choices=window_titles)

        # 获取指定窗口对象
        try:
            window = gw.getWindowsWithTitle(window_title)[0]
        except IndexError:
            print(f"未找到标题为 '{window_title}' 的窗口.")
            exit()

        # 获取窗口的位置和大小
        x, y, width, height = window.left, window.top, window.width, window.height

        # 打印窗口的位置和大小
        print(f"截取窗口的位置: ({x}, {y}), 大小: {width}x{height}")

        # 使用mss进行截图
        with mss.mss() as sct:
            bbox = {'top': y, 'left': x, 'width': width, 'height': height}
            screenshot = sct.grab(bbox)

            # 将截取的结果转换为PIL图像格式
            img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')

            # 保存截取的图像
            img.save('screenshot_window.png')
        
        print("指定窗口的截图已保存.")
        return img
    def capture_window4():
        import mss
        import pygetwindow as gw
        import easygui
        import win32gui
        from PIL import Image

        # 获取所有窗口标题
        window_titles = gw.getAllTitles()

        # 选择要截图的窗口
        window_title = easygui.choicebox(msg="请选择要截图的窗口", choices=window_titles)

        # 获取指定窗口对象
        try:
            window = gw.getWindowsWithTitle(window_title)[0]
        except IndexError:
            print(f"未找到标题为 '{window_title}' 的窗口.")
            exit()

        # 将指定窗口置于最上方
        win32gui.SetForegroundWindow(window._hWnd)

        # 给予一点时间，让窗口渲染
        import time
        time.sleep(0.1)

        # 获取窗口的位置和大小
        x, y, width, height = window.left, window.top, window.width, window.height

        # 打印窗口的位置和大小
        print(f"截取窗口的位置: ({x}, {y}), 大小: {width}x{height}")

        # 使用mss进行截图
        with mss.mss() as sct:
            bbox = {'top': y, 'left': x, 'width': width, 'height': height}
            screenshot = sct.grab(bbox)

            # 将截取的结果转换为PIL图像格式
            img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')

            # 保存截取的图像
            img.save('screenshot_window.png')

        print("指定窗口的截图已保存.")
        return img
class WindowRecord:
    def record_window3(window):
        import cv2
        import mss
        import pygetwindow as gw
        import easygui
        from PIL import Image
        
        print(window)
        window_title = window.title
        print(f"开始录制窗口: {window_title}")
        use = True
        wt = window_title + '_Liveing ' + str(uuid.uuid4())
        wt = wt.encode('utf-8').decode('utf-8')
        print(f"录制窗口的名称: {wt}")
        screen_width, screen_height = pyautogui.size()
        
        while use:
            
            # 获取窗口的位置和大小
            x, y, width, height = window.left, window.top, window.width, window.height
            if x + width > screen_width:
                width = screen_width - x
            if y + height > screen_height:
                height = screen_height - y
            if x < 0:
                width += x
                x = 0
            if y < 0:
                height += y
                y = 0

            # 打开cv2的窗口
            cv2.namedWindow(wt, cv2.WINDOW_NORMAL)
            cv2.resizeWindow(wt, width, height)
            # 使用mss进行截图
            try:
                with mss.mss() as sct:
                    bbox = {'top': y, 'left': x, 'width': width, 'height': height}
                    screenshot = sct.grab(bbox)

                    # 将截取的结果转换为PIL图像格式
                    img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')
                    # 显示截取的图像
                    cv2.imshow(wt, cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
                    # 按下Esc键退出录制
                    if cv2.waitKey(1) == 27:
                        use = False
            except:
                print("录制失败.")
        cv2.destroyAllWindows()
        print("录制结束.")
def SelectWindowFromTitle(t):
    import mss
    import pygetwindow as gw
    import easygui
    from PIL import Image
    # 获取所有窗口标题
    window_titles = gw.getAllTitles()

    # 选择窗口
    window_title = easygui.choicebox(msg="请选择要录制的窗口", choices=window_titles)
    # 获取指定窗口对象
    try:
        window = gw.getWindowsWithTitle(window_title)[0]
    except IndexError:
        print(f"未找到标题为 '{window_title}' 的窗口.")
        exit()
        return window
def SelectWindowFromTitleAndTaskPID(t):
    import mss
    import pygetwindow as gw
    import easygui
    from PIL import Image
    import win32gui
    import win32process
    # 获取所有窗口标题
    window_titles = gw.getAllTitles()
    
    
    # 获取所有的窗口进程PID
    pids = [win32process.GetWindowThreadProcessId(i)[1] for i in win32gui.EnumWindows()]

    # 选择窗口
    window_title = easygui.choicebox(msg=f"请选择要{t}的窗口", choices=window_titles)
    # 通过PID和窗口标题获取指定窗口对象
    try:
        pid = [p for p in pids if gw.getWindowsWithTitle(window_title)[0]._hWnd in [win32gui.GetWindow(i) for i in win32gui.FindWindowEx(None, None)]][0]
        window = gw.getWindowsWithPID(pid)[0]
    except IndexError:
        print(f"未找到标题为 '{window_title}' 的窗口.")
        exit()
def SelectWindowFromAllAtts(t):
    import mss
    import pygetwindow as gw
    import easygui
    from PIL import Image
    import win32gui
    import win32process
    windows = gw.getAllWindows()
    ws = []
    for w in windows:
        ws.append(f"{w.title} [left: {w.left}, top: {w.top}, width: {w.width}, height: {w.height}, pid: {win32process.GetWindowThreadProcessId(w._hWnd)[1]}, hwnd: {w._hWnd}] | index: {windows.index(w)}")
    w = easygui.choicebox(msg=f"请选择要{t}的窗口", choices=ws)
    return windows[int(w.split(" | index: ")[-1])]


WindowRecord.record_window3(SelectWindowFromAllAtts("录制"))














